import {BadRequestException, Controller, Delete, Get, Inject, Post, Query, Req} from "@nestjs/common";
import {Public} from "~/modules/auth/decorators/public.decorator";
import {ApiBody, ApiConsumes, ApiOperation, ApiTags} from "@nestjs/swagger";
import {GoodsDeleteDto, GoodsSaveDto} from "~/modules/shop/goods/goods.dto";
import {FastifyRequest} from "fastify";
import {AuthUser} from "~/modules/auth/decorators/auth-user.decorator";
import {plainToInstance} from "class-transformer";
import {validate} from "class-validator";
import {GoodsService} from "~/modules/shop/goods/goods.service";

@ApiTags("Shop - 商品")
@Controller('shop/goods')
export class GoodsController {

  @Inject()
  private readonly goodsService: GoodsService

  @Post()
	@Public()
  @ApiOperation({summary: '添加商品'})
  @ApiConsumes('multipart/form-data')
  @ApiBody({type: GoodsSaveDto})
  async add(@Req() req: FastifyRequest) {
    try {
      const params: Record<string, any> = req.body

      params.file = params.file[0]

      const goodsSaveDto = plainToInstance(GoodsSaveDto, req.body)
      const errors = await validate(goodsSaveDto)

      if (errors.length) {
        // 取出 errors[0].constraints 中的第一个错误信息，constraints为一个对象结构
        const message = Object.values(errors[0].constraints)[0]
        throw new BadRequestException(message)
      }

      // 业务逻辑
      return await this.goodsService.save(goodsSaveDto)
    }
    catch (error) {
      throw new BadRequestException(error?.message ?? '上传失败')
    }
  }

  @Delete()
  @ApiOperation({summary: '删除商品'})
  @ApiBody({type: GoodsDeleteDto})
  async remove(@Query() query: GoodsDeleteDto) {
    try {
      await this.goodsService.remove(query.id)

      return null
    }
    catch (error) {
      throw new BadRequestException(error?.message ?? '删除失败')
    }
  }

  @Get()
  @ApiOperation({summary: '查询商品'})
  async find() {
    return await this.goodsService.find()
  }
}
